<?php

class MienNamController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        $this->view->headTitle("Miền Nam")->setSeparator("|");
        $this->view->headScript()->appendFile($this->view->baseUrl("js/mien-nam.js"));
    }

    public function indexAction()
    {
        // action body
    }

    public function insertAction()
    {
        // action body
        if($this->_request->isPost()){
            $data = $this->_request->getParams();
            unset($data['module']);
            unset($data['controller']);
            unset($data['action']);
            $DbTable = new Application_Model_DbTable_Regnumbers();
            $Row = $DbTable->createRow();
            
            $idUser = Zend_Auth::getInstance()->getIdentity()->idUsers;
            $date = explode("/",$data['date']);
            
            $Row->DateRegistry = "{$date[2]}-{$date[1]}-{$date[0]}";
            $Row->Channel      = $data['channel'];
            $Row->TypeRegistry = $data['type'];
            $Row->Number  = $data['number'][0];
            $Row->BPrice  = $data['price'][0];
            $Row->FPrice  = $data['price'][1];
            $Row->LPrice  = $data['price'][2];
            $Row->Number1 = $data['number'][1];
            $Row->Number2 = $data['number'][2];
            $Row->VsPrice = $data['price'][3];
            $Row->Users   = $idUser;
            
            if($data['type']==0){
                $Row->TotalPrice = (($Row->BPrice*14) + ($Row->FPrice+$Row->LPrice)*0.8)*1000;
            }else{
                $Row->TotalPrice = $Row->VsPrice*30*1000;
            }
            if($Row->Channel==0){
                $Row->TotalPrice*=2;
            }
            $id = $Row->save();
            
            // Dò số trúng
            $DbTable->UpdateStatus(new Zend_Date("{$date[2]}/{$date[1]}/{$date[0]}","yyyy/MM/dd"));
            
            return $this->_helper->json->sendJson($id);   
        }
        return $this->_helper->json->sendJson(false);
    }

    public function deleteAction()
    {
        // action body
        if($this->_request->isPost()){
            $id = $this->_request->getParam("id");
            if(isset($id)) {
                $DbTable = new Application_Model_DbTable_Regnumbers();
                $Row = $DbTable->find($id)->current();
                if($Row){
                    $Row->delete();
                    return $this->_helper->json->sendJson(true);
                }
                return $this->_helper->json->sendJson(false);
            }
            return $this->_helper->json->sendJson(false);
        }
        return $this->_helper->json->sendJson(false);
    }

    public function editAction()
    {
        // action body
    }

    public function viewAction()
    {
        // action body
        if($this->_request->isPost()){
            $date = $this->_request->getParam("date");
            $date = explode("/",$date);
            $dbTable = new Application_Model_DbTable_Regnumbers();
            $user = Zend_Auth::getInstance()->getIdentity()->idUsers;
            $select = $dbTable->select(); 
            $select->where("DateRegistry LIKE ?","{$date[2]}-{$date[1]}-{$date[0]}%")
                   ->where("Users=?",$user);
            $RowSets = $dbTable->fetchAll($select);
            $rData = array();
            
            foreach($RowSets as $row) {
                if($row->TypeRegistry==1) { // Đá
                    $rData[$row->Channel][] = array(
                        "id"    => $row->idRegNumbers,
                        "number"=>"{$row->Number1}x{$row->Number2}",
                        "type"  =>$row->VsPrice,
                        "total" =>$row->TotalPrice,
                        "status"=>$row->Status
                    );
                }else{
                    $rData[$row->Channel][] = array(
                        "id"    => $row->idRegNumbers,
                        "number"=>$row->Number,
                        "type"  =>"({$row->BPrice}){$row->FPrice}-{$row->LPrice}",
                        "total" =>$row->TotalPrice,
                        "status"=>$row->Status
                    );  
                }
            }
        }
        $this->_helper->json->sendJson($rData);        
    }

    public function overAction()
    {
        // action body
        if($this->_request->isPost()){
            $date = $this->_request->getParam("date");
            $date = explode("/",$date);
            $DbTable = new Application_Model_DbTable_Regnumbers();
            $select = $DbTable->select();
            $select->from("regnumbers",array("numrow"=>"COUNT(*)","totalprice"=>"SUM(TotalPrice)"))
                   ->where("DateRegistry LIKE ?","{$date[2]}-{$date[1]}-{$date[0]}%"); 
            $data1 = $DbTable->fetchRow($select)->toArray();
            
            $select = $DbTable->select();
            $select->from("regnumbers",array("numvip"=>"COUNT(*)","vipprice"=>"SUM(TotalPrice)"))
                   ->where("DateRegistry LIKE ?","{$date[2]}-{$date[1]}-{$date[0]}%")
                   ->where("Status!=?",0); 
            $data2 = $DbTable->fetchRow($select)->toArray();
            
            $data = array_merge($data1,$data2);
            $this->_helper->json->sendJson($data);
        }
    }

    public function updateResultAction()
    {
        // action body
        $channels = array(array("tien-giang"=>"Tiền Giang", "kien-giang"=>"Kiên Giang"),
                          array("ho-chi-minh"=>"Hồ Chí Minh", "dong-thap"=>"Đồng Tháp"),
                          array("ben-tre"=>"Bến Tre", "vung-tau"=>"Vũng Tàu"),
                          array("dong-nai"=>"Đồng Nai", "can-tho"=>"Cần Thơ"),
                          array("tay-ninh"=>"Tây Ninh", "an-giang"=>"An Giang"),
                          array("vinh-long"=>"Vĩnh Long", "binh-duong"=>"Bình Dương"),
                          array("ho-chi-minh"=>"Hồ Chí Minh", "long-an"=>"Long An"));
                                           
        list($day,$month, $year) = explode("/",$this->_request->getParam("date",date("d/m/Y")));
        $dbResult = new Application_Model_DbTable_Result();
        $findResult = $dbResult->fetchRow($dbResult->select()->where("DateOut LIKE ?","{$year}-{$month}-{$day}"));
        
        if(!$findResult) {            
            $zDate = new Zend_Date("{$day}/{$month}/{$year}","dd/MM/yyyy");   
            $channels = $channels[$zDate->get(Zend_Date::WEEKDAY_DIGIT)];
            
            $channel = 1;
            foreach($channels as $key=>$name){
                $client = new Zend_Http_Client("http://ketqua.net/xo-so-{$key}.php?ngay={$day}/{$month}/{$year}");
                $content = $client->request()->getBody();
                $dom = new Zend_Dom_Query($content);
                $results = $dom->query("#ketqua table.bot");
                
               if($results->current()!=null) {
                    $textResult = $results->current()->textContent;
                    $textResult = preg_replace("#(.*)Đặc Biệt(.*?)Nhận KQXS(.*)#is",'$2',$textResult);
                    $nums = preg_split("#\D{2,}#",trim($textResult));
                    $lv4 = array(substr($nums[9],0,5), substr($nums[9],6,5));
                    $book = array(
                        "DateOut"=> $zDate->toString("yyyy-MM-dd"),
                        "Channel" => $channel,
                        "L0" => $nums[1], "L1" => $nums[2],"L2" => $nums[3],"L3" => $nums[4],
                        "L4" => $nums[5],"L5" => $nums[6],"L6" => $nums[7],"L7" => $nums[8],
                        "L8" => $lv4[0],"L9" => $lv4[1],"L10"=> $nums[10],"L11"=> $nums[11],
                        "L12"=> $nums[12],"L13"=> $nums[13],"L14"=> $nums[14],"L15"=> $nums[15],
                        "L16"=> $nums[16],"L17"=> $nums[17]
                    );
                    $channel++;
                    $dbResult->insert($book);
               }
            }           
        }
               
        $findResult = $dbResult->fetchAll($dbResult->select()->where("DateOut LIKE ?","{$year}-{$month}-{$day}"));
        $this->_helper->json->sendJson($findResult->toArray());
    }
}













